import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../data/models/destination_model.dart';
import '../../providers/destination_provider.dart';

class DestinationDetailPage extends StatefulWidget {
  final String destinationId;

  const DestinationDetailPage({Key? key, required this.destinationId})
    : super(key: key);

  @override
  State<DestinationDetailPage> createState() => _DestinationDetailPageState();
}

class _DestinationDetailPageState extends State<DestinationDetailPage>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  DestinationDetail? _destination;
  bool _isLoading = true;
  String? _errorMessage;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 4, vsync: this);
    _loadDestinationDetail();
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  Future<void> _loadDestinationDetail() async {
    try {
      setState(() {
        _isLoading = true;
        _errorMessage = null;
      });

      final provider = context.read<DestinationProvider>();
      final destination = await provider.getDestinationDetail(
        widget.destinationId,
      );

      setState(() {
        _destination = destination;
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _errorMessage = '加载失败: $e';
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body:
          _isLoading
              ? const Center(child: CircularProgressIndicator())
              : _errorMessage != null
              ? _buildErrorWidget()
              : _destination != null
              ? _buildContent()
              : _buildNotFoundWidget(),
    );
  }

  Widget _buildErrorWidget() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.error_outline, size: 64, color: Colors.grey.shade400),
          const SizedBox(height: 16),
          Text(_errorMessage!, style: TextStyle(color: Colors.grey.shade600)),
          const SizedBox(height: 16),
          ElevatedButton(
            onPressed: _loadDestinationDetail,
            child: const Text('重试'),
          ),
        ],
      ),
    );
  }

  Widget _buildNotFoundWidget() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.location_off, size: 64, color: Colors.grey.shade400),
          const SizedBox(height: 16),
          Text('目的地不存在', style: TextStyle(color: Colors.grey.shade600)),
          const SizedBox(height: 16),
          ElevatedButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('返回'),
          ),
        ],
      ),
    );
  }

  Widget _buildContent() {
    return NestedScrollView(
      headerSliverBuilder: (context, innerBoxIsScrolled) {
        return [
          SliverAppBar(
            expandedHeight: 300,
            floating: false,
            pinned: true,
            backgroundColor: Colors.blue,
            flexibleSpace: FlexibleSpaceBar(
              title: Text(
                _destination!.name,
                style: const TextStyle(
                  color: Colors.white,
                  fontWeight: FontWeight.bold,
                ),
              ),
              background: Stack(
                fit: StackFit.expand,
                children: [
                  Image.network(
                    _destination!.image,
                    fit: BoxFit.cover,
                    errorBuilder: (context, error, stackTrace) {
                      return Container(
                        color: Colors.grey.shade300,
                        child: const Icon(
                          Icons.location_on,
                          size: 64,
                          color: Colors.grey,
                        ),
                      );
                    },
                  ),
                  Container(
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        begin: Alignment.topCenter,
                        end: Alignment.bottomCenter,
                        colors: [
                          Colors.transparent,
                          Colors.black.withOpacity(0.7),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ];
      },
      body: Column(
        children: [
          // 基本信息
          _buildBasicInfo(),

          // 标签页
          _buildTabBar(),

          // 标签页内容
          Expanded(
            child: TabBarView(
              controller: _tabController,
              children: [
                _buildIntroTab(),
                _buildAttractionsTab(),
                _buildMapTab(),
                _buildNearbyTab(),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildBasicInfo() {
    return Container(
      padding: const EdgeInsets.all(16),
      color: Colors.white,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(Icons.location_on, color: Colors.blue, size: 20),
              const SizedBox(width: 4),
              Text(
                _destination!.country,
                style: TextStyle(color: Colors.grey.shade600, fontSize: 14),
              ),
              const Spacer(),
              Icon(Icons.star, color: Colors.amber, size: 20),
              const SizedBox(width: 4),
              Text(
                '${_destination!.rating}',
                style: const TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: 16,
                ),
              ),
              Text(
                ' (${_destination!.reviewCount})',
                style: TextStyle(color: Colors.grey.shade600, fontSize: 14),
              ),
            ],
          ),
          const SizedBox(height: 8),

          // 标签
          if (_destination!.tags.isNotEmpty)
            Wrap(
              spacing: 8,
              runSpacing: 4,
              children:
                  _destination!.tags.map((tag) {
                    return Container(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 8,
                        vertical: 4,
                      ),
                      decoration: BoxDecoration(
                        color: Colors.blue.shade50,
                        borderRadius: BorderRadius.circular(12),
                      ),
                      child: Text(
                        tag,
                        style: TextStyle(
                          color: Colors.blue.shade700,
                          fontSize: 12,
                        ),
                      ),
                    );
                  }).toList(),
            ),

          const SizedBox(height: 12),

          // 价格和时间信息
          Row(
            children: [
              _buildInfoChip(
                Icons.attach_money,
                '¥${_destination!.priceRange.min}-${_destination!.priceRange.max}',
              ),
              const SizedBox(width: 12),
              _buildInfoChip(Icons.access_time, _destination!.visitDuration),
              const SizedBox(width: 12),
              _buildInfoChip(Icons.wb_sunny, _destination!.bestSeason),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildInfoChip(IconData icon, String text) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: Colors.grey.shade100,
        borderRadius: BorderRadius.circular(8),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(icon, size: 16, color: Colors.grey.shade600),
          const SizedBox(width: 4),
          Text(
            text,
            style: TextStyle(color: Colors.grey.shade600, fontSize: 12),
          ),
        ],
      ),
    );
  }

  Widget _buildTabBar() {
    return Container(
      color: Colors.white,
      child: TabBar(
        controller: _tabController,
        labelColor: Colors.blue,
        unselectedLabelColor: Colors.grey,
        indicatorColor: Colors.blue,
        tabs: const [
          Tab(text: '介绍'),
          Tab(text: '景点'),
          Tab(text: '地图'),
          Tab(text: '附近'),
        ],
      ),
    );
  }

  Widget _buildIntroTab() {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '目的地介绍',
            style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
          ),
          const SizedBox(height: 12),
          Text(
            _destination!.description,
            style: const TextStyle(fontSize: 14, height: 1.6),
          ),

          const SizedBox(height: 24),

          if (_destination!.transportation != null) ...[
            const Text(
              '交通信息',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 12),
            _buildTransportationInfo(),
            const SizedBox(height: 24),
          ],

          const Text(
            '实用信息',
            style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
          ),
          const SizedBox(height: 12),
          _buildPracticalInfo(),
        ],
      ),
    );
  }

  Widget _buildTransportationInfo() {
    if (_destination!.transportation == null) return const SizedBox();

    final transport = _destination!.transportation!;
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            if (transport.airport?.isNotEmpty == true) ...[
              _buildTransportItem(Icons.flight, '机场', transport.airport!),
              const SizedBox(height: 8),
            ],
            if (transport.publicTransport?.isNotEmpty == true) ...[
              _buildTransportItem(
                Icons.directions_bus,
                '公共交通',
                transport.publicTransport!,
              ),
              const SizedBox(height: 8),
            ],
            if (transport.driveTime?.isNotEmpty == true) ...[
              _buildTransportItem(
                Icons.directions_car,
                '自驾',
                transport.driveTime!,
              ),
            ],
          ],
        ),
      ),
    );
  }

  Widget _buildTransportItem(IconData icon, String type, String info) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Icon(icon, size: 20, color: Colors.blue),
        const SizedBox(width: 8),
        Text('$type: ', style: const TextStyle(fontWeight: FontWeight.bold)),
        Expanded(child: Text(info)),
      ],
    );
  }

  Widget _buildPracticalInfo() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            if (_destination!.language?.isNotEmpty == true)
              _buildPracticalItem(
                Icons.language,
                '语言',
                _destination!.language!,
              ),
            if (_destination!.currency?.isNotEmpty == true)
              _buildPracticalItem(
                Icons.monetization_on,
                '货币',
                _destination!.currency!,
              ),
            if (_destination!.timezone?.isNotEmpty == true)
              _buildPracticalItem(
                Icons.access_time,
                '时区',
                _destination!.timezone!,
              ),
            if (_destination!.climate?.isNotEmpty == true)
              _buildPracticalItem(
                Icons.wb_cloudy,
                '气候',
                _destination!.climate!,
              ),
          ],
        ),
      ),
    );
  }

  Widget _buildPracticalItem(IconData icon, String label, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4),
      child: Row(
        children: [
          Icon(icon, size: 18, color: Colors.grey.shade600),
          const SizedBox(width: 8),
          SizedBox(
            width: 60,
            child: Text(
              '$label:',
              style: TextStyle(color: Colors.grey.shade600),
            ),
          ),
          Expanded(child: Text(value)),
        ],
      ),
    );
  }

  Widget _buildAttractionsTab() {
    if (_destination!.attractions.isEmpty) {
      return const Center(child: Text('暂无景点信息'));
    }

    return ListView.builder(
      padding: const EdgeInsets.all(16),
      itemCount: _destination!.attractions.length,
      itemBuilder: (context, index) {
        final attraction = _destination!.attractions[index];
        return Card(
          margin: const EdgeInsets.only(bottom: 12),
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Row(
              children: [
                Container(
                  width: 80,
                  height: 80,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(8),
                    color: Colors.grey.shade200,
                  ),
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(8),
                    child: Image.network(
                      attraction.image,
                      fit: BoxFit.cover,
                      errorBuilder: (context, error, stackTrace) {
                        return Icon(
                          Icons.place,
                          color: Colors.grey.shade400,
                          size: 32,
                        );
                      },
                    ),
                  ),
                ),
                const SizedBox(width: 16),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        attraction.name,
                        style: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      const SizedBox(height: 4),
                      Text(
                        attraction.description,
                        style: TextStyle(
                          color: Colors.grey.shade600,
                          fontSize: 14,
                        ),
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                      ),
                      const SizedBox(height: 8),
                      Row(
                        children: [
                          Icon(Icons.star, color: Colors.amber, size: 16),
                          const SizedBox(width: 4),
                          Text(
                            '${attraction.rating}',
                            style: const TextStyle(fontSize: 14),
                          ),
                          const SizedBox(width: 16),
                          Text(
                            '¥${attraction.priceRange}',
                            style: TextStyle(
                              color: Colors.blue,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _buildMapTab() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.map, size: 64, color: Colors.grey.shade400),
          const SizedBox(height: 16),
          Text('地图功能开发中...', style: TextStyle(color: Colors.grey.shade600)),
          const SizedBox(height: 8),
          Text(
            '坐标: ${_destination!.coordinates.lat}, ${_destination!.coordinates.lng}',
            style: TextStyle(color: Colors.grey.shade500, fontSize: 12),
          ),
        ],
      ),
    );
  }

  Widget _buildNearbyTab() {
    if (_destination!.nearbyDestinations.isEmpty) {
      return const Center(child: Text('暂无附近目的地'));
    }

    return ListView.builder(
      padding: const EdgeInsets.all(16),
      itemCount: _destination!.nearbyDestinations.length,
      itemBuilder: (context, index) {
        final nearby = _destination!.nearbyDestinations[index];
        return Card(
          margin: const EdgeInsets.only(bottom: 12),
          child: ListTile(
            leading: Container(
              width: 50,
              height: 50,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(8),
                color: Colors.grey.shade200,
              ),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(8),
                child: Image.network(
                  nearby.image,
                  fit: BoxFit.cover,
                  errorBuilder: (context, error, stackTrace) {
                    return Icon(Icons.place, color: Colors.grey.shade400);
                  },
                ),
              ),
            ),
            title: Text(nearby.name),
            subtitle: Text(nearby.country),
            trailing: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Icon(Icons.star, color: Colors.amber, size: 16),
                const SizedBox(width: 4),
                Text('${nearby.rating}'),
              ],
            ),
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder:
                      (context) =>
                          DestinationDetailPage(destinationId: nearby.id),
                ),
              );
            },
          ),
        );
      },
    );
  }
}
